/*
 * @Author: wwssaabb
 * @Date: 2021-06-25 14:49:37
 * @LastEditTime: 2021-06-27 20:10:45
 * @FilePath: \demo\todo_list\src\store\mutations.ts
 */
import { State, state, TodoItem } from "./state";
import { MutationTree } from "vuex";

export enum MutationType {
  CreateItem = "CREATE_ITEM",
  SetItem = "SET_ITEM",
  CompleteItem = "COMPLETE_ITEM",
  DeleteItem = "DELETE_ITEM",
  SetLoading = "SET_LOADING",
}

export type Mutations = {
  [MutationType.CreateItem](state: State, item: TodoItem): void;
  [MutationType.SetItem](state: State, items: TodoItem[]): void;
  [MutationType.CompleteItem](
    state: State,
    items: Partial<TodoItem> & { id: number }
  ): void;
  [MutationType.DeleteItem](
    state: State,
    items: Partial<TodoItem> & { id: number }
  ): void;
  [MutationType.SetLoading](state: State, value: boolean): void;
};

export const mutations: MutationTree<State> & Mutations = {
  [MutationType.CreateItem](state, item) {
    state.todoList.unshift(item);
  },
  [MutationType.SetItem](state, items) {
    state.todoList = items;
  },
  [MutationType.CompleteItem](state, newItem) {
    let item = state.todoList.find((i) => (i.id = newItem.id));
    if (!item) return;
    item = { ...item, ...newItem };
  },
  [MutationType.DeleteItem](state, item) {
    let index = state.todoList.map(i=>i.id).indexOf(item.id)
    state.todoList.splice(index,1)
  },
  [MutationType.SetLoading](state, value) {
    state.loading = value;
  },
};
